﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{
        await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml");
    }
    @{
        await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml");
    }

    <link href="/css/HpuByYield.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>HpuByYieldReport</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            color: #ffffff;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        #board {
            padding: 0.2rem 0.2rem;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        .ZebraNo {
            background-color: #e8f1f9;
        }

        .ZebraTo {
            background-color: #ffffff;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }

        td.percentage {
            border-color: transparent;
        }

        #left-table-body {
            background-image: url('../images/loading.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }

        /*END*/
        /*明细模态*/
        .show_mode {
            border-radius: 0.1rem;
            position: absolute;
            z-index: 99;
            height: 10.6rem;
            width: 100%;
            /*text-align: center;*/
            background: #a2c2e2;
            display: none;
        }

        .show_mode > .contentdetail > div {
            color: black;
            height: 33.3%;
            width: 50%;
            float: left;
            border-block: solid #ffffff 1px;
        }

        .show_mode > .contentdetail > div > label {
            color: black;
        }

        .detail {
            color: black;
            height: 3rem;
            width: 100%;
            /*background-color: #dfe4ee;*/
        }

        .mode_close {
            float: right;
        }

        .mode_close:hover {
            background-color: #848690;
        }
        /*end*/

    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="HpuByYieldToExport('HpuByYield')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title note">@Label.Note_HPUYieldReport</div>
                    <div id="board">
                        <div class="query">
                            <input type="datetime-local" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time" style="width:1.9rem">
                            <span class="exampleInputProject tle">@Label.To</span>
                            <input type="datetime-local" id="enddate" name="enddate" placeholder="@Label.Start@Label.End" style="width:1.9rem">
                            <select id="cmb_prod_type" name="ProdType" placeholder="select prodtype">
                                <option value="ALL">@Label.ALL</option>
                                <option value="Normal">@Label.Fresh</option>
                                <option value="Rework">@Label.Rework</option>
                                <option value="RMA">@Label.RMA</option>
                            </select>
                            <select id="cmb_proj_code" placeholder="select ProjCode">
                                 @* 
                                 <option value="ALL" selected>@Label.ALL</option>
                                 <option value="">@Label.PleaseSelect</option> 
                                 *@
                                <option value="NCCSAD" selected>CDGR4</option>
                               
                            </select>
                            <select id="cmb_product" placeholder="select Product">
                                @*   
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option> 
                                *@
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="ROSA_ADN">ROSA_ADN</option>
                                <option value="TOSA_ADN">TOSA_ADN</option>
                                <option value="MODULE_ADN">MODULE_ADN</option>
                            </select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                        </div>
                        <div id="table-container">
                            <div id="left-table" class="rightTop">
                                <div id="left-table-body"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="show_mode">
            <div style="width:100%; height:0.3rem;">
                <div class="mode_close" style="height:100%;margin-right:10px;line-height:0.3rem;"><label style="font-size:0.17rem;color:white;">关闭&times;</label></div>
            </div>
            <div class="contentdetail"></div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $(".show_mode").css("display", "none");
        $('.mode_close').click(function () {
            $(".show_mode").css("display", "none");
            $(".contentdetail").empty();
            $(".contentdetail div").remove();
        });
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });
            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_HPUYieldReport)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear();
                var myMonth = myDate.getMonth() + 1;
                var myToday = myDate.getDate();
                var myDay = myDate.getDay();
                var myHour = myDate.getHours();
                var myMinute = myDate.getMinutes();
                var mySecond = myDate.getSeconds();
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit + Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });

            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });
        });

        //定时查询
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            //每隔10m执行一次
            Tabtimer = setInterval(function () {
                var endDate = new Date($("#enddate").val());
                if (endDate > new Date()) {
                    getdate();
                }
            }, 10 * 60 * 1000);
        }

        $(function () {
            var startDate = new Date();
            startDate.setDate(startDate.getDate() - 7);
            startDate.setHours(7, 0, 0, 0);
            var endDate = new Date();
            endDate.setDate(endDate.getDate() + 1);
            endDate.setHours(7, 0, 0, 0);
            var startdatetime = startDate.toLocaleDateString('sv-SE') + 'T' + startDate.toTimeString().slice(0, 5);
            $('#startdate').val(startdatetime);
            var enddatetime = endDate.toLocaleDateString('sv-SE') + 'T' + endDate.toTimeString().slice(0, 5);
            $('#enddate').val(enddatetime);
            //ComboxAction();
            setTimeout(function () {
                $('#cmb_prod_type').val('Normal').change();
                $('#cmb_proj_code').val('NCCSAD').trigger('change');
                Getdata();
            }, 850);
        })

        var Getdata = function () {
            getdate();
            TabInterval();
        }

        /*报表导出*/
        var ExportType;
        var HpuByYieldToExport = function (type) {
            ExportType = type;
            var formData = new FormData();
            formData.append('excelname', ExportType);
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $('#cmb_product').val() == null ? "ALL" : $('#cmb_product').val());
            formData.append('type', $('#cmb_prod_type').val());
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            var url = api + "/ReportAction/GetHpuByYieldToExport";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }
        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }

        function loadingshow() {
            $('#left-table-body').css('background-image', 'url("../images/loading.gif")');
            $('#left-table-body').css('background-size', '0.8rem 0.8rem');
            $('#left-table-body').css('background-repeat', 'no-repeat');
            $('#left-table-body').css('background-position', 'center');
        }
        function loadingnone() {
            $('#left-table-body').css('background-image', 'none');
        }

        //获取数据
        var Tab;
        var getdate = function () {
            $('#btn_query').prop('disabled', true);
            var header_key = {
                start: $('#startdate').val(),
                end: $('#enddate').val()
            };
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.product_code = $('#cmb_product').val();
            pam.type = $('#cmb_prod_type').val()
            pam.header_key = JSON.stringify(header_key);
            if (pam.proj_code !== "-1") {
                loadingshow();
                $("#left-table-body").empty();
                $("#myTable").empty();
                $.ajax({
                    type: "POST",
                    url: api + "/ReportAction/GetHpuByYield",
                    data: pam,
                    dataType: "json",
                    async: true,
                    success: function (dt) {
                        loadingnone();
                        $('#btn_query').prop('disabled', false);
                        Tab = dt.ReturnData;
                        prod_yield_boarddata();
                    }
                });
            }
        }

        //工序良率
        var prod_yield_boarddata = function () {
            $('#btn_query').prop('disabled', false);
            var data = Tab.Table.map(item => {
                let newItem = Object.assign({}, item);
                delete newItem.SORT;
                return newItem;
            });
            $("#myTable").empty();
            $("#left-table-body").empty();
            var left_table_html = `
            <table id="myTable" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                <thead><tr></tr></thead>
                <tbody id="yield_tbody"></tbody>
                <tfoot><tr></tr></tfoot>
            </table>`;
            $("#left-table-body").append(left_table_html);
            var table = $('#myTable');
            var tbody = table.find('tbody');
            var headerRow = table.find('thead tr');
            var headers = Object.keys(data[0]).filter(key => !['ROW_NUM', 'ROWSPAN'].includes(key));
            headers.forEach(function (header) {
                headerRow.append('<th>' + header + '</th>');
            });
            var finalyield = 1;
            var affecthour = 0;
            data.forEach(function (row, index) {
                index++;
                var table_tr_dt = "";
                headers.forEach(function (header, columnindex) {
                    let bagcolor = "";
                    if (header === "FINAL_YIELD") {
                        finalyield = finalyield*parseFloat(row[header].substring(0, row[header].indexOf("%"))) / 100;
                    }
                    if (header == "AFFECT_MAN_HOUR") {
                        affecthour += parseFloat(row[header]);
                    }
                    if (header === "FINAL_YIELD" || header === "ACCU_HPU") {
                        const actualValue = header === "FINAL_YIELD" ? parseFloat(row[header].replace("%", "")) : parseFloat(row[header]);
                        const targetValue = header === "FINAL_YIELD" ? parseFloat(row["YIELD_TARGET"].replace("%", "")) : parseFloat(row["CUM_HPU_TARGET"]);
                        const difference = targetValue - actualValue;
                        if (difference >= 5) {
                            bagcolor = "style='background-color:#fc6999';";  
                        } 
                        if (difference > 0) {
                            bagcolor = "style='background-color:rgb(222,255,150);'";
                        }
                        if (difference == 0) {
                            bagcolor = "style='background-color:rgb(155,255,150);'";
                        }
                        if (difference < 0) {
                            bagcolor = "style='background-color:rgb(43,230,150);'";
                        }
                    }
                    table_tr_dt += `<td class="truncate" ${bagcolor}>${row[header]}</td>`;
                });
                var newRow = $(`<tr class="${(parseInt(index) % 2) > 0 ? "ZebraNo" : "ZebraTo"}">${table_tr_dt}</tr>`);
                tbody.append(newRow);
            });
            var tfootRow = table.find('tfoot tr');
            tfootRow.append(`<th colspan="3">汇总</th>`);
            tfootRow.append(`<th colspan="2">FinalYield</th>`);
            tfootRow.append(`<th>${parseFloat((finalyield * 100).toFixed(2))}%</th>`);
            tfootRow.append(`<th colspan="1"></th>`);
            tfootRow.append(`<th colspan="1"></th>`);
            tfootRow.append(`<th colspan="2">AffectHour</th>`);
            tfootRow.append(`<th colspan="1">${parseFloat(affecthour.toFixed(3))}</th>`);
        };

    </script>
</body>
</html>
